import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:just_audio/just_audio.dart';

List _playersList = [];

class PlacePlayerWidget extends StatefulWidget {
  PlacePlayerWidget(
      {Key? key,
      required this.audioUrl,
      this.isShowLoading = true,
      this.iconSize = 30})
      : super(key: key);
  final String audioUrl;
  final bool isShowLoading;
  final double iconSize;
  @override
  State<PlacePlayerWidget> createState() => _PlacePlayerWidgetState();
}

class _PlacePlayerWidgetState extends State<PlacePlayerWidget> {
  final _player = AudioPlayer();
  RxInt _playState = 0.obs;
  @override
  void dispose() {
    _playState.value = 0;
    // _playersList.clear();
    _player.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _player.setUrl(widget.audioUrl);
    _player.pause();
    _playersList.add(_player);
    _player.playerStateStream.listen((playerState) {
      final processingState = playerState.processingState;
      if (processingState == ProcessingState.loading ||
          processingState == ProcessingState.buffering) {
        if (widget.isShowLoading) _playState.value = -1;
      } else if (!playerState.playing) {
        _playState.value = 0;
      } else if (processingState != ProcessingState.completed) {
        _playState.value = 1;
      } else {
        _player.seek(Duration.zero);
        _player.pause();
      }
    });
    return Obx(() {
      return _playState.value == -1
          ? Container(
              margin: const EdgeInsets.all(8.0),
              width: widget.iconSize + 2,
              height: widget.iconSize + 2,
              child: CircularProgressIndicator(
                backgroundColor: Get.theme.primaryColorDark,
                strokeWidth: 5.0,
              ),
            )
          : IconButton(
              iconSize: widget.iconSize,
              color: Color(0xfff3701f),
              onPressed: () {
                _playState.value == 0 ? _play() : _player.pause();
              },
              icon: Icon(
                _playState.value == 0 ? Icons.play_circle : Icons.pause_circle,
              ));
    });
  }

  void _play() {
    for (var player in _playersList) {
      player.pause();
    }
    _player.play();
  }
}
